package net.wicp.tams.common.grpc;

import java.io.IOException;

import io.grpc.BindableService;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Conf;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.grpc.connector.ConnectorServer;

@Slf4j
public class Main {
	private Server server;

	private void start() throws IOException {
		int port = Integer.parseInt(Conf.get("common.grpc.server.port"));
		String services = Conf.get("common.grpc.server.service");
		ServerBuilder<?> serverBuilder = ServerBuilder.forPort(port).addService(ConnectorServer.getInst());
		if (StringUtil.isNotNull(services)) {
			String[] servers = services.split(",");
			for (String serverstr : servers) {
				try {
					BindableService newInstance = (BindableService) Class.forName(serverstr).newInstance();
					serverBuilder.addService(newInstance);
				} catch (Exception e) {
					log.error("加载服务失败:{}", serverstr);
					throw new RuntimeException("加载服务失败:" + serverstr);
				}
			}
		}
		server = serverBuilder.build();
		server.start();
		log.info("server started, listening on " + port);

		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				// Use stderr here since the logger may have been reset by its JVM shutdown
				// hook.
				System.err.println("*** shutting down gRPC server since JVM is shutting down");
				if (server != null) {
					server.shutdown();
				}
				System.err.println("*** server shut down");
			}
		});
	}

	/**
	 * Await termination on the main thread since the grpc library uses daemon
	 * threads.
	 */
	private void blockUntilShutdown() throws InterruptedException {
		if (server != null) {
			server.awaitTermination();
		}
	}

	/***
	 * 主程序入口
	 * 
	 * @param args
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws IOException, InterruptedException {
		final Main server = new Main();
		server.start();
		server.blockUntilShutdown();
	}

}
